const express = require('express');
// 引入方法模块
const methods = require('./methods');

const router = express.Router();

//获取json数据
var data = require('./data.json');

// 首页
router.get('/', (req, res) => {
  // 渲染首页
  res.render('index.html', { list: data.Books });
});

// 添加页面
router.get('/add', (req, res) => {
  res.render('add.html');
});
router.post('/add', (req, res) => {
  const body = req.body;
  methods.add(body,(err) => {
    if(err){
      return status(500).send('Server err');
    }
    res.redirect('/')
  })
});

// 修改页面
router.get('/edit', (req, res) => {
  methods.FindID(req.query,(book) => {
    res.render('edit.html', {
      arr: book,
    });
  })
});
router.post('/edit', (req, res) => {
  var body = req.body;
  methods.edit(body,(err) => {
    if(err){
      return status(500).send('Server err')
    }
    res.redirect('/')
  })
  
});

// 删除页面
router.get('/delete', (req, res) => {
  methods.delete(req.query,(err) => {
    if(err){
      status(500).send('Server err')
    }
    res.redirect('/');
  })
  /* var a
  req.query.id = parseInt(req.query.id)
  data.movies.forEach((item,index) => {
    index += 1
    if(index === req.query.id){
      return a = item
    }
  })

  data.movies.splice(a.id - 1,1)

  fs.writeFile('./data.json',JSON.stringify({movies:data.movies}), (err) => {
    if(err){
      throw err;
    }
    console.log('xie ru cheng gong');
  }) */

  
});
module.exports = router;
